// src/screens/auth/LoginScreen.tsx
import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  Platform,
  ScrollView,
  ActivityIndicator, KeyboardAvoidingView,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { RootStackParamList } from '../../navigation/types.ts'
import { StackNavigationProp } from '@react-navigation/stack';
type NavigationProp = StackNavigationProp<RootStackParamList>;
import { useDispatch, useSelector } from 'react-redux';
import Icon from 'react-native-vector-icons/MaterialIcons';
import LinearGradient from 'react-native-linear-gradient';
import Toast from 'react-native-toast-message';
import { AppDispatch, RootState } from '../../store/store';
import { login } from '../../store/slices/authSlice';

const LoginScreen: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { isLoading, error } = useSelector((state: RootState) => state.auth);
  const navigation = useNavigation<NavigationProp>();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);

  const handleLogin = async () => {
    if (!email || !password) {
      Toast.show({
        type: 'error',
        text1: '请填写所有字段',
      });
      return;
    }

    try {
      await dispatch(login({ email, password })).unwrap();
      Toast.show({
        type: 'success',
        text1: '登录成功',
      });
    } catch (error) {
      Toast.show({
        type: 'error',
        text1: '登录失败',
        text2: error as string,
      });
    }
  };

  return (
      <KeyboardAvoidingView
          style={styles.container}
          behavior="height"
      >
        <LinearGradient
            colors={['#667eea', '#fff']}
            style={styles.gradient}
        >
          <ScrollView
              contentContainerStyle={styles.scrollContent}
              showsVerticalScrollIndicator={false}
          >
            <View style={styles.header}>
              <Icon name="smart-toy" size={80} color="#fff" />
              <Text style={styles.title}>AI工具箱</Text>
              <Text style={styles.subtitle}>登录您的账户</Text>
            </View>

            <View style={styles.form}>
              {/* 邮箱输入框 */}
              <View style={styles.inputWrapper}>
                <Text style={styles.inputLabel}>邮箱地址</Text>
                <View style={[styles.inputContainer, email.length > 0 && styles.inputFocused]}>
                  <View style={styles.iconContainer}>
                    <Text style={styles.iconText}>📧</Text>
                  </View>
                  <TextInput
                      style={styles.input}
                      placeholder="请输入您的邮箱"
                      placeholderTextColor="#a0a0a0"
                      value={email}
                      onChangeText={setEmail}
                      keyboardType="email-address"
                      autoCapitalize="none"
                      textAlignVertical="center"
                      multiline={false}
                  />
                </View>
              </View>

              {/* 密码输入框 */}
              <View style={styles.inputWrapper}>
                <Text style={styles.inputLabel}>密码</Text>
                <View style={[styles.inputContainer, password.length > 0 && styles.inputFocused]}>
                  <View style={styles.iconContainer}>
                    <Text style={styles.iconText}>🔒</Text>
                  </View>
                  <TextInput
                      style={styles.input}
                      placeholder="请输入您的密码"
                      placeholderTextColor="#a0a0a0"
                      value={password}
                      onChangeText={setPassword}
                      secureTextEntry={!showPassword}
                      textAlignVertical="center"
                      multiline={false}
                  />
                  <TouchableOpacity
                      onPress={() => setShowPassword(!showPassword)}
                      style={styles.eyeButton}
                  >
                    <Text style={styles.eyeIcon}>
                      {showPassword ? '👁️' : '🙈'}
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>

              <TouchableOpacity style={styles.forgotPassword}>
                <Text style={styles.forgotPasswordText}>忘记密码？</Text>
              </TouchableOpacity>

              <TouchableOpacity
                  style={[styles.loginButton, isLoading && styles.loginButtonDisabled]}
                  onPress={handleLogin}
                  disabled={isLoading}
              >
                <LinearGradient
                    colors={isLoading ? ['#ccc', '#999'] : ['#667eea', '#764ba2']}
                    style={styles.loginButtonGradient}
                >
                  {isLoading ? (
                      <View style={styles.loadingContainer}>
                        <ActivityIndicator color="#fff" size="small" />
                        <Text style={styles.loginButtonText}>登录中...</Text>
                      </View>
                  ) : (
                      <Text style={styles.loginButtonText}>登 录</Text>
                  )}
                </LinearGradient>
              </TouchableOpacity>

              <View style={styles.divider}>
                <View style={styles.dividerLine} />
                <Text style={styles.dividerText}>或</Text>
                <View style={styles.dividerLine} />
              </View>

              <View style={styles.socialLogin}>
                <TouchableOpacity style={[styles.socialButton, styles.googleButton]}>
                  <LinearGradient
                      colors={['#fff', '#f8f9fa']}
                      style={styles.socialButtonGradient}
                  >
                    <Text style={styles.googleIcon}>G</Text>
                  </LinearGradient>
                </TouchableOpacity>
              </View>

              <View style={styles.footer}>
                <Text style={styles.footerText}>还没有账户？</Text>
                <TouchableOpacity onPress={() => navigation.navigate('Register')}>
                  <Text style={styles.signupLink}>立即注册</Text>
                </TouchableOpacity>
              </View>
            </View>
          </ScrollView>
        </LinearGradient>
      </KeyboardAvoidingView>

  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  gradient: {
    flex: 1,
  },
  scrollContent: {
    flexGrow: 1,
    justifyContent: 'center',
    paddingHorizontal: 30,
    paddingVertical: 50,
  },
  header: {
    alignItems: 'center',
    marginBottom: 40,
  },
  title: {
    fontSize: 32,
    fontWeight: 'bold',
    color: '#fff',
    marginTop: 20,
  },
  subtitle: {
    fontSize: 16,
    color: '#fff',
    opacity: 0.8,
    marginTop: 10,
  },
  form: {
    backgroundColor: 'rgba(255, 255, 255, 0.95)',
    borderRadius: 24,
    padding: 30,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 20,
    },
    shadowOpacity: 0.15,
    shadowRadius: 30,
    elevation: 8,
  },
  // 输入框包装器
  inputWrapper: {
    marginBottom: 24,
  },
  // 输入框标签
  inputLabel: {
    fontSize: 14,
    fontWeight: '600',
    color: '#374151',
    marginBottom: 8,
    marginLeft: 4,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f8fafc',
    borderRadius: 16,
    borderWidth: 1,
    borderColor: '#e2e8f0',
    paddingHorizontal: 16,
    height: 56,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.05,
    shadowRadius: 4,
    elevation: 2,
  },
  // 输入框聚焦状态
  inputFocused: {
    borderColor: '#667eea',
    backgroundColor: '#fff',
    shadowColor: '#667eea',
    shadowOpacity: 0.15,
    shadowRadius: 8,
    elevation: 4,
  },
  // 图标容器
  iconContainer: {
    width: 32,
    height: 32,
    borderRadius: 8,
    backgroundColor: 'rgba(102, 126, 234, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 12,
  },
  input: {
    flex: 1,
    fontSize: 16,
    color: '#1f2937',
    fontWeight: '500',
    height: '100%',
    textAlignVertical: 'center',
  },
  // 眼睛按钮
  eyeButton: {
    width: 32,
    height: 32,
    borderRadius: 8,
    backgroundColor: 'rgba(102, 126, 234, 0.1)',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 8,
  },
  eyeIcon: {
    fontSize: 16,
  },
  forgotPassword: {
    alignSelf: 'flex-end',
    marginBottom: 24,
    marginTop: -8,
  },
  forgotPasswordText: {
    color: '#667eea',
    fontSize: 14,
    fontWeight: '600',
  },
  loginButton: {
    borderRadius: 16,
    height: 56,
    marginBottom: 24,
    shadowColor: '#667eea',
    shadowOffset: {
      width: 0,
      height: 8,
    },
    shadowOpacity: 0.3,
    shadowRadius: 16,
    elevation: 8,
  },
  loginButtonDisabled: {
    shadowOpacity: 0.1,
  },
  loginButtonGradient: {
    flex: 1,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loginButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: 'bold',
    letterSpacing: 1,
  },
  loadingContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  divider: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 20,
  },
  dividerLine: {
    flex: 1,
    height: 1,
    backgroundColor: '#ddd',
  },
  dividerText: {
    marginHorizontal: 10,
    color: '#999',
  },
  socialLogin: {
    flexDirection: 'row',
    justifyContent: 'center',
    marginBottom: 24,
  },
  socialButton: {
    width: 56,
    height: 56,
    borderRadius: 16,
    marginHorizontal: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 4,
    },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 4,
  },
  socialButtonGradient: {
    flex: 1,
    borderRadius: 16,
    justifyContent: 'center',
    alignItems: 'center',
  },
  googleButton: {
    shadowColor: '#DB4437',
  },
  facebookButton: {
    shadowColor: '#4267B2',
  },
  appleButton: {
    shadowColor: '#000',
  },
  // 图标文字样式
  iconText: {
    fontSize: 18,
    textAlign: 'center',
  },
  // Google图标样式
  googleIcon: {
    fontSize: 22,
    fontWeight: 'bold',
    color: '#DB4437',
  },
  // Facebook图标样式
  facebookIcon: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    fontFamily: 'serif',
  },
  // Apple图标样式
  appleIcon: {
    fontSize: 20,
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  footerText: {
    color: '#666',
    fontSize: 14,
  },
  signupLink: {
    color: '#667eea',
    fontSize: 14,
    fontWeight: 'bold',
    marginLeft: 5,
  },
});

export default LoginScreen;